/*************************************************************************************
 * Nombre del archivo: Main.java
 * Universidad del Valle de Guatemala
 * Curso: Sistemas Operativos
 * @author martin
 *          Martín Guzmán 08041
 * Fecha: Enero de 2010
 * Descripción:
*************************************************************************************/

import java.io.File;
import java.util.Scanner;
import java.util.LinkedList;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;
import java.io.File;
import java.io.FileWriter;
import java.text.NumberFormat;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.PiePlot;

public class Main {

    /**
     * @param args the command line arguments
     */
    public static boolean restart=false;

    public static void main(String[] args) {
        do{
            restart=false;
            //se crea un hilo de ejecución con el Shell del proyecto
            Thread shell = new Thread(new Shell());
            //se crea un hilo de ejecución con el Shell del proyecto
            Thread cpu = new Thread(new CPU());
            //se inicia el shell
            shell.start();
            //se inicia el cpu
            cpu.start();


            try{
                shell.join();
                CPU.fileSystem.flushFS();
                //Imprimir_estadisticas();

                cpu.stop();
                shell.stop();
                
            }catch (Exception ie) {}

        }while(restart);
    }

/*
    private static void Imprimir_estadisticas() {
        Graficas_procesos();
        Graficas_colas();
    }
 */
    /*
    private static void Graficas_procesos() {

        int SO_Excecution_time = 0;
        int SO_IO_Waiting_time = 0;
        int SO_Waiting_time = 0;
        int SO_Quantum_Waiting_time = 0;
        int SO_Semaphore_Waiting_time = 0;
        int SO_Response_time = 0;
        //int SO_TurnArround_time = 0;

        for(int i=0;i<CPU.Todos_Procesos.size();i++){

            Proceso proc = CPU.Todos_Procesos.get(i);

            int Excecution_time = proc.excecution_time;
            SO_Excecution_time += Excecution_time;
            int Waiting_time = proc.waiting_time;
            SO_Waiting_time += Waiting_time;
            int IO_Waiting_time = proc.io_waiting_time;
            SO_IO_Waiting_time += IO_Waiting_time;
            int Quantum_Waiting_time = proc.quantum_waiting_time;
            SO_Quantum_Waiting_time +=Quantum_Waiting_time;
            int Semaphore_Waiting_time = proc.semaphore_waiting_time;
            SO_Semaphore_Waiting_time +=Semaphore_Waiting_time;
            int Response_time = proc.response_time;
            SO_Response_time +=Response_time;

            /*
            System.out.println("Excecution time: "+(Excecution_time));
            System.out.println("Waiting time: "+(Waiting_time));
            System.out.println("Response time: "+(Response_time));
            System.out.println("TurnArround time: "+(TurnArround_time));
             */
/*
            // Create a simple pie chart
            DefaultPieDataset pieDataset = new DefaultPieDataset();
            pieDataset.setValue("Excecution time", new Integer(Excecution_time));
            pieDataset.setValue("Waiting time (Ready State)", new Integer(Waiting_time));
            pieDataset.setValue("IO Waiting time", new Integer(IO_Waiting_time));
            //pieDataset.setValue("Quantum Waiting time", new Integer(Quantum_Waiting_time));
            pieDataset.setValue("Semaphore Waiting time", new Integer(Semaphore_Waiting_time));
            pieDataset.setValue("Response time", new Integer(Response_time));
            JFreeChart chart = ChartFactory.createPieChart("Proceso "+i+"\n"+proc.archivo.getName(),pieDataset,true,true,false);

            //chart.setBackgroundPaint(new Color(222, 222, 255));
            PiePlot plot = (PiePlot)chart.getPlot();
            //plot.setBackgroundPaint(Color.white);
            plot.setCircular(true);
            plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0} ({1}) ({2})", NumberFormat.getNumberInstance(), NumberFormat.getPercentInstance()));

            try {
                ChartUtilities.saveChartAsPNG(new File("/home/martin/Desktop/Gráficos/Procesos/Proceso_"+i+".png"), chart, 600,400);
            } catch (Exception e) {
                System.out.println("Error creando grafico.");
            }


        }
        Grafica_SO(SO_Excecution_time,SO_IO_Waiting_time,SO_Quantum_Waiting_time,SO_Semaphore_Waiting_time,SO_Response_time,SO_Waiting_time);
        Grafica_Uso_CPU(SO_Excecution_time);
    }
    private static void Graficas_colas() {

        // Create a simple pie chart
        DefaultPieDataset pieDataset = new DefaultPieDataset();

        for(int i=0;i<CPU.lista_colas.size();i++){

            pieDataset.setValue(CPU.lista_colas.get(i).getName()+"\n"+CPU.lista_colas.get(i).getType(), new Integer(CPU.lista_colas.get(i).getExcecution_time_in_this()));
        }
        JFreeChart chart = ChartFactory.createPieChart("Execution time en cada cola",pieDataset,true,true,false);
        PiePlot plot = (PiePlot)chart.getPlot();
        plot.setCircular(true);
        plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0} ({1}) ({2})", NumberFormat.getNumberInstance(), NumberFormat.getPercentInstance()));

        try {
            ChartUtilities.saveChartAsPNG(new File("/home/martin/Desktop/Gráficos/Colas/Execution time en colas.png"), chart, 800,600);
        } catch (Exception e) {
            System.out.println("Error creando grafico.");
        }
    }
    private static void Grafica_SO(int SO_Excecution_time, int SO_IO_Waiting_time, int SO_Quantum_Waiting_time, int SO_Semaphore_Waiting_time, int SO_Response_time, int SO_Waiting_time) {
        String texto = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
        texto +="<pie>\n";
        System.out.println("Throughput (Procesos terminados / Número de ticks de ejecución): "+(double)(CPU.Cola_Procesos_Terminados.size())/(double)(SO_Excecution_time));
        texto+="<slice title=\"Excecution time (prom)\">"+SO_Excecution_time+"</slice>\n";
        texto+="<slice title=\"Waiting time (Ready state) (prom)\">"+SO_Waiting_time+"</slice>\n";
        texto+="<slice title=\"IO Waiting time (prom)\">"+SO_IO_Waiting_time+"</slice>\n";
        //texto+="<slice title=\"Quantum Waiting time (prom)\">"+SO_Quantum_Waiting_time+"</slice>\n";
        texto+="<slice title=\"Semaphore Waiting time (prom)\">"+SO_Semaphore_Waiting_time+"</slice>\n";
        texto+="<slice title=\"Response time\">"+SO_Response_time+"</slice>\n";

        texto +="</pie>\n";

        File TextFile = new File("/home/martin/Desktop/Gráficos/Sistema Operativo/ampie/ampie_data.xml");
        FileWriter TextOut;
        try {
            TextOut = new FileWriter(TextFile, false);
            TextOut.write(texto);
            TextOut.close();
        } catch (Exception ex) {

        }
    }
    private static void Grafica_Uso_CPU(int SO_Excecution_time) {
        // Create a simple pie chart
        DefaultPieDataset pieDataset = new DefaultPieDataset();

        int contador_ticks = CPU.contador_ticks;

        pieDataset.setValue("CPU running", new Integer(SO_Excecution_time));
        pieDataset.setValue("CPU waiting", new Integer(contador_ticks-SO_Excecution_time));

        JFreeChart chart = ChartFactory.createPieChart("Uso de CPU",pieDataset,true,true,false);
        PiePlot plot = (PiePlot)chart.getPlot();
        plot.setCircular(true);
        plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0} ({1}) ({2})", NumberFormat.getNumberInstance(), NumberFormat.getPercentInstance()));

        try {
            ChartUtilities.saveChartAsPNG(new File("/home/martin/Desktop/Gráficos/Sistema Operativo/Uso de CPU.png"), chart, 800,600);
        } catch (Exception e) {
            System.out.println("Error creando grafico.");
        }
    }*/

    /***********************************************
     * Método: Print
     * Uso: Imprime el contenido de print
     * @param print
     * @return void
    ***********************************************/
    public static void Print(String print){
        System.out.println(print);
    }

}